package com.grademaster.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grademaster.common.R;
import com.grademaster.dto.ClassPageDto;
import com.grademaster.entity.Classes;
import com.grademaster.mapper.ClassesMapper;
import com.grademaster.service.ClassesService;
import com.grademaster.util.LoginUtil;
import com.grademaster.vo.ClassVO;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
* @author Administrator
* @description 针对表【classes(班级表)】的数据库操作Service实现
* @createDate 2024-06-25 13:56:47
*/
@Service
public class ClassesServiceImpl extends ServiceImpl<ClassesMapper, Classes>
    implements ClassesService {

    @Autowired
    private ClassesMapper classesMapper;

    /**
     * 根据教师id查询班级列表
     *
     * @param teacherId
     * @return
     */
    @Override
    public R listByTeacher(Long teacherId) {
        //判断是否登录
        StpUtil.isLogin();

        //获取教师id
        //判断是不是超级管理员，不是超级管理员只能查询自己的Id相关的学期数据
        String userId = null;
        if(!LoginUtil.isAdmin()){
            userId = LoginUtil.getLoginUserId();
        }
        //获取数据
        List<String> classesList = classesMapper.selectDistinctClassNamesByTeacherId(userId);

        return R.success(classesList);
    }

    /**
     * 获取所有班级
     *
     * @return
     */
    @Override
    public R getAllClasses() {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        return R.success(this.list());
    }

    /**
     * 获取所有班级，分页
     *
     * @param classPageDto
     * @return
     */
    @Override
    public R getAllClassesByPage(ClassPageDto classPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        List<ClassVO> voList = classesMapper.selectClassesByCondition(
                classPageDto.getGradeName()
                , classPageDto.getMajorName()
                , classPageDto.getClassName()
                , classPageDto.getPage()
                , classPageDto.getPageSize()
        );
        int count = classesMapper.countClassesByCondition(
                classPageDto.getGradeName()
                , classPageDto.getMajorName()
                , classPageDto.getClassName()
        );
        Page<ClassVO> page = new Page<>(classPageDto.getPage(), classPageDto.getPageSize(),count);
        page.setRecords(voList);
        return R.success(page);
    }
    /**
     * 导出班级信息
     *
     * @param classPageDto
     * @return
     */
    @Override
    public ResponseEntity exportExcel(ClassPageDto classPageDto) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return ResponseEntity.badRequest().build();
        }
        List<ClassVO> voList = classesMapper.selectClassesByCondition(
                classPageDto.getGradeName()
                , classPageDto.getMajorName()
                , classPageDto.getClassName()
                , 1
                , 2000
        );
        Workbook workbook = new XSSFWorkbook();

        // Create a sheet named "Classes"
        Sheet sheet = workbook.createSheet("Classes");

        // Create header row
        Row headerRow = sheet.createRow(0);
        String[] headers = {"班级ID", "年级名称", "专业名称", "班级名称"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // Create data rows
        int rowNum = 1;
        for (ClassVO classVO : voList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(classVO.getClassId());
            row.createCell(1).setCellValue(classVO.getGradeName());
            row.createCell(2).setCellValue(classVO.getMajorName());
            row.createCell(3).setCellValue(classVO.getClassName());
        }

        // Auto-size columns (optional)
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write workbook to ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Create InputStreamResource to wrap ByteArrayInputStream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        InputStreamResource resource = new InputStreamResource(inputStream);

        // Set response headers
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=classes.xlsx");

        // Return ResponseEntity with Excel file as body
        return ResponseEntity.ok()
                .headers(httpHeaders)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);

    }

    /**
     * 添加或修改班级信息
     *
     * @param classes
     * @return
     */
    @Override
    public R addOrEditClass(Classes classes) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        if (classes.getClassId() != null){
            return R.success(this.updateById(classes));
        }
        //添加专业
        return R.success(this.save(classes));
    }

    /**
     * 删除班级
     *
     * @param classId
     * @return
     */
    @Override
    public R deleteClass(String classId) {
        StpUtil.isLogin();
        //既不是成绩管理员也不是管理员
        if (!LoginUtil.isAdmin()){
            return R.error("权限不足");
        }
        String[] ids = classId.split(",");
        for (String id : ids) {
            this.removeById(id);
        }
        return R.success("删除成功");
    }


}




